package org.django4j;

import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

/**
 * 定义了django4j支持的参数数据类型，这里定义为只支持java中的原型数据类型。对于用户提交的表单
 * 数据，可以通过其他的工具类从HttpServletRequest获得数据来组装。 
 * 如果要添加新的支持的数据类型，需要注意：
 * 1）在supportedArgTypes中添加支持的数据类型声明
 * 2）在toType()方法中执行数据类型转换
 */
public class TypedArgument {
    private static final String dateFormat = "yyyyMMdd";
    private static Set<Class> supportedArgTypes = new HashSet<Class>();
    
    static {
        supportedArgTypes.add(String.class);
        supportedArgTypes.add(int.class);
        supportedArgTypes.add(Integer.class);
        supportedArgTypes.add(Double.class);
        supportedArgTypes.add(double.class);
        supportedArgTypes.add(Float.class);
        supportedArgTypes.add(float.class);
        supportedArgTypes.add(Long.class);
        supportedArgTypes.add(long.class);
        supportedArgTypes.add(Short.class);
        supportedArgTypes.add(short.class);
        supportedArgTypes.add(java.util.Date.class);        
    }

    public static boolean isSupported(Class type){
        return supportedArgTypes.contains(type);
    }

    public static Object toType(String str, Class type) throws Exception{
        if (str == null || type == null ){
            throw new IllegalArgumentException (
                    "neither of arguments of toType(String,Class) can be null.");
        }
        if (!supportedArgTypes.contains(type)){
            throw new IllegalStateException("the argument type(" 
                    + type + ") isn't supported.");
        }
        
        Object value = str;
        if (type.equals(int.class)){
            value = new Integer(str).intValue();
        }
        else if (type.equals(Integer.class)){
            value = new Integer(str);
        }
        else if (type.equals(long.class)){
            value = new Long(str).longValue();
        }
        else if (type.equals(Long.class)){
            value = new Long(str);
        }
        else if (type.equals(short.class)){
            value = new Short(str).shortValue();
        }
        else if (type.equals(Short.class)){
            value = new Short(str);
        }
        else if (type.equals(double.class)){
            value = new Double(str).doubleValue();
        }
        else if (type.equals(Double.class)){
            value = new Double(str);
        }
        else if (type.equals(java.util.Date.class)){
            value = new SimpleDateFormat(dateFormat).parse(str);
        }
        else if (type.equals(String.class)){
            value = str;
        }
        else if (type.equals(float.class)){
            value = new Float(str).floatValue();
        }
        else if (type.equals(Float.class)){
            value = new Float(str);
        }
        
        return value;
    }
}
